package antidestiny.utilib.ui.fragment.explorer;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.FileFilter;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import antidestiny.utilib.Aide;
import antidestiny.utilib.R;
import antidestiny.utilib.io.FileUtils;
import antidestiny.utilib.io.Progress;
import antidestiny.utilib.ui.view.AutoProgressBar;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ExplorerFragment extends Fragment implements PopupMenu.OnMenuItemClickListener {

    private OnListFragmentInteractionListener mListener;
    private ExplorerManagerI manager;
    File rootFile;
    int chooseRequest;
    View confirmButtonContainer;
    TextView title;

    Bundle args = new Bundle();
    final String KEY_BUNDLE = "bundle";
    final String KEY_FILE = "file";
    final String KEY_TITLE = "title";


    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ExplorerFragment() {
        setArguments(new Bundle());
    }

    /**
     * 当前显示的文件夹
     */
    File dirFile;

    /**
     * @param dir 文件夹。如果是文件，则使用上一级文件夹
     */
    void setDir(@Nullable String dir) {
        if (dir == null) {
            this.dirFile = null;
            return;
        }
        File dirFile = new File(dir);
        if (!dirFile.exists()) dirFile = null;
        else if (dirFile.isFile()) dirFile = dirFile.getParentFile();
        this.dirFile = dirFile;
    }

    /**
     * 想要在Fragment显示之前就设定好文件夹，就用这个方法创建实例
     *
     * @param dir     显示的文件夹
     * @param root    根目录
     * @param manager 管理器接口
     * @return 实例
     */
    public static ExplorerFragment newInstance(File dir, File root, @NonNull ExplorerManagerI manager) {
        ExplorerFragment fragment = new ExplorerFragment();
        fragment.init(dir, root, manager);
        return fragment;
    }

    public static ExplorerFragment newInstance(File dir, ExplorerManagerI manager) {
        return newInstance(dir, dir, manager);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void init(File dir, File root, @NonNull ExplorerManagerI manager) {
        this.manager = manager;
        setDir(dir.getAbsolutePath());
        this.rootFile = root;
    }

    /**
     * 更新列表显示
     */
    public void refresh() {
        if (adapter!=null)
        this.adapter.update();
    }

    boolean selectMode = true;

    /**
     * 设置是否为选择模式
     * 默认为选择文件模式
     */
    public void selectMode(boolean on) {
        selectMode = on;
    }

    MyFileRecyclerViewAdapter adapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) args = savedInstanceState;

        View view = inflater.inflate(R.layout.fragment_file_list, container, false);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.fileList);
        Context context = view.getContext();
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        confirmButtonContainer = view.findViewById(R.id.confirm_button_container);
        //设置标题
        title = (TextView) view.findViewById(R.id.title);
        String titleString = args.getString(KEY_TITLE);
        if (titleString != null) {
            title.setText(titleString);
            title.setVisibility(View.VISIBLE);
        }

        adapter = new MyFileRecyclerViewAdapter(recyclerView);
        confirmButtonContainer.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (manager != null) {
                    manager.onChooseResult(chooseRequest, chooseResult());
                }

            }
        });


        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle(KEY_BUNDLE, args);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * 删除文件或者文件夹
     */
    private void del(final File file) {
        String msg = "";
        if (file.isFile())
            msg = String.format(getString(R.string.msg_dialog_delete_file), file.getName());
        else if (file.isDirectory())
            msg = String.format(getString(R.string.msg_dialog_delete_dir), file.getName()
                    , FileUtils.getAllSubFileCount(file));

        new AlertDialog.Builder(getContext()).setTitle(getString(R.string.title_dialog_delete))
                .setMessage(msg).setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (file.isFile()) {
                            if (!file.delete()) {
                                //noinspection ConstantConditions
                                Snackbar.make(getView(), "文件删除失败：" + file.getName(), Snackbar.LENGTH_LONG).show();
                            }
                            return;
                        }
                        if (file.isDirectory()) {
                            final Progress progress = new Progress();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    FileUtils.removeDir(file, progress);
                                }
                            }).start();
                            final AutoProgressBar bar = new AutoProgressBar(getContext(), progress, new AutoProgressBar.ProgressListener() {
                                @Override
                                public void atTheEnd() {
                                    refresh();
                                }
                            });
                            new AlertDialog.Builder(getContext()).setTitle("删除")
                                    .setView(bar).setPositiveButton(android.R.string.ok, null).show();


                        }
                    }
                }).show();


    }

    //TODO
    private void rename(final File f) {
        final EditText edit = new EditText(getContext());
        String name = f.getName();
        edit.setText(name);
        edit.setSelection(0, name.lastIndexOf('.'));
        new AlertDialog.Builder(getContext()).setTitle("重命名")
                .setView(edit).setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String result = edit.getText().toString();
                        String errMsg = null;
                        File renamed = new File(f.getParent() + '/' + result);
                        if (result.length() == 0) {
                            errMsg = "请输入合理的文件名";
                        } else {
                            if (renamed.exists()) {
                                errMsg = "文件名已被占用";
                            }
                        }

                        if (errMsg != null) {
                            //noinspection ConstantConditions
                            Snackbar.make(getView(), errMsg, Snackbar.LENGTH_LONG).show();
                            return;
                        }
                        if (!f.renameTo(renamed)) {
                            //noinspection ConstantConditions
                            Snackbar.make(getView(), "重命名出错", Snackbar.LENGTH_LONG).show();
                        }
                    }
                }).show();
    }

    private final String MARK_PASTE_BOARD_FILE = "[file]:";
    /**
     * 真表示当前为剪贴操作，反之为复制操作
     */
    private boolean pasteBoard_cut = false;
    @NonNull
    private String pasteBoard = "";

    private void cut(@Nullable File file) {
        if (file == null) return;
        pasteBoard = MARK_PASTE_BOARD_FILE + file.getAbsolutePath();
        pasteBoard_cut = true;
        if (manager != null) manager.onPasteBoardChange(file);
    }

    private void copy(@Nullable File file) {
        if (file == null) return;
        pasteBoard = MARK_PASTE_BOARD_FILE + file.getAbsolutePath();
        pasteBoard_cut = false;
        if (manager != null) manager.onPasteBoardChange(file);
    }

    public void pasteFile() {
        final File dir = getCurrentDir();
        if (dir == null) return;
        if (!dir.exists()) return;
        if (!dir.isDirectory()) return;

        pasteBoard = "";
        pasteBoard_cut = false;
        final Progress progress = new Progress();
        AutoProgressBar bar = new AutoProgressBar(getContext(), progress, new AutoProgressBar.ProgressListener() {
            @Override
            public void atTheEnd() {
                refresh();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = getFileFromPasteBoard();
                if (file != null) {
                    FileUtils.copy(file, dir, progress);
                    if (pasteBoard_cut) {
                        //noinspection ResultOfMethodCallIgnored
                        file.delete();
                    }
                }
                refresh();
            }
        }).start();

        new AlertDialog.Builder(getContext()).setTitle("复制文件")
                .setView(bar).setPositiveButton(android.R.string.ok, null).show();
    }

    /**
     * 从剪贴板取得文件
     *
     * @return 剪贴板没有文件时返回空。返回的文件需进一步检查，以确定其是否存在，等等。
     */
    @Nullable
    private File getFileFromPasteBoard() {
        if (!pasteBoard.startsWith(MARK_PASTE_BOARD_FILE)) return null;
        return new File(pasteBoard.substring(MARK_PASTE_BOARD_FILE.length(), pasteBoard.length()));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_explorer, menu);
    }

    /**
     * 也进行文件管理器项目长按菜单处理
     */
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Intent msg = item.getIntent();
        String path = msg.getStringExtra(KEY_FILE);
        if (path != null) {//是和文件有关的操作
            File file = new File(path);
            if (!file.exists()) return true;

            if (item.getItemId() == R.id.item_cut) {
                cut(file);
            }
            else if (item.getItemId()==R.id.item_copy){
                copy(file);
            }else if (item.getItemId() == R.id.item_delete) {
                del(file);
            } else if (item.getGroupId() == R.id.item_rename) {
                rename(file);
            }
            return true;
        }
        if (item.getItemId() == R.id.item_paste) {
            pasteFile();
        }


        return false;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        boolean onListFragmentInteraction(FileItem item, View v);

        boolean onFileItemClick(FileItem item, View v);

        boolean onFileItemLongClick(FileItem item, View v);

        boolean onFileSystemChange(File file);
    }

    /**
     * @param name 文件夹的名称
     * @return 成功返回1；未知原因返回0；文件夹已存在返回-1；当前工作文件夹为空返回-2；
     */
    public int mkDir(String name) {
        if (this.dirFile == null) return -2;
        File toMk = new File(dirFile.getAbsolutePath() + '/' + name);
        if (toMk.exists()) return -1;
        boolean success = toMk.mkdirs();
        if (!success) return 0;
        refresh();
        return 1;

    }

    /**
     * 返回上一级
     */
    public void back() {
        if (dirFile == null) return;
        if (dirFile.equals(rootFile)) {
            if (manager != null) manager.onChooseResult(chooseRequest, null);
        } else
            adapter.setDirAndUpdate(dirFile.getParentFile());
    }

    public int getConfirmViewVisibility() {
        return confirmButtonContainer.getVisibility();
    }

    public File getCurrentDir() {
        return dirFile;
    }

    ExplorerFileFilter fileFilter;

    /**
     * 选择文件时对文件进行过滤，界面会因此刷新留下符合条件的文件。
     * 如果过滤方式不需要指定文件类型，那么suffix就可以为null
     */
    public void chooseRequest(int chooseRequest, int filterType, String suffix, FileFilter fileFilter) {
        this.chooseRequest = chooseRequest;
        this.fileFilter=new ExplorerFileFilter(filterType,suffix,fileFilter);
        refresh();
    }

    public List<FileItem> chooseResult(){
        ArrayList<FileItem> items=new ArrayList<>();
        if (adapter==null)return items;
        List<FileItem> allFiles = adapter.getFiles();
        int allFileLength = allFiles.size();
        for (int i = 0; i < allFileLength; i++) {
            if (allFiles.get(i).checked&&fileFilter.accept(new File(allFiles.get(i).path)))
                items.add(allFiles.get(i));
        }
        return items;
    }

    /**
     * 设置标题，比如“请选择文件”
     *
     * @param s
     */
    public void setTitle(final String s) {
        args.putString(KEY_TITLE, s);
        if (title != null) {
            title.setText(s);
            title.setVisibility(View.VISIBLE);
        }
    }

    public interface onPreparedListener {
        void prepared();
    }

    /**
     * 刷新文件选择个数并显示
     */
    public void refreshCheckItemCount() {
        if (adapter == null) return;
        TextView textViewCount = (TextView) confirmButtonContainer
                .findViewById(R.id.selected_file_count);
        if (textViewCount.getVisibility() != View.VISIBLE) return;
        textViewCount.setText(String.format("%d个文件已选择",adapter.getCheckedItemCount()));

    }


    class MyFileRecyclerViewAdapter extends RecyclerView.Adapter<MyFileRecyclerViewAdapter.ViewHolder> {

        final private List<FileItem> mValues = new ArrayList<>();
        RecyclerView recyclerView;
        boolean selectMode = true;

        public MyFileRecyclerViewAdapter(RecyclerView recyclerView) {

            this.recyclerView = recyclerView;
            setDirAndUpdate(ExplorerFragment.this.dirFile);
        }

        private File getCurrentDir() {
            return ExplorerFragment.this.dirFile;
        }

        private File getRoorDir() {
            return ExplorerFragment.this.rootFile;
        }

        private void setCurrentDir(@Nullable File dir) {
            ExplorerFragment.this.dirFile = dir;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.fragment_file, parent, false);
            if (!ExplorerFragment.this.selectMode)
                view.findViewById(R.id.checkbox_select).setVisibility(View.GONE);
            return new ViewHolder(view);
        }

        /**
         * @param dir 为空时清空显示
         */
        void setDirAndUpdate(@Nullable File dir) {
            setCurrentDir(dir);
            update();
        }

        void update() {
            Aide.t("正在更新，当前文件夹是：" + controlFragment.dirFile);
            if (getCurrentDir() != null && fileFilter!=null) {
                List<FileItem> items = fileFilter.filtrate(getCurrentDir());
                mValues.clear();
                mValues.addAll(items);
            }
            Collections.sort(mValues);
            recyclerView.setAdapter(this);
            refreshConfirmButtonVisibility();
        }

        View.OnClickListener itemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewHolder holder = (ViewHolder) v.getTag();
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    boolean die = mListener.onListFragmentInteraction(holder.mItem, v);
                    if (!die) die = mListener.onFileItemClick(holder.mItem, v);
                    if (die) return;
                }
                File file;
                if ((file = new File(holder.mItem.path)).isDirectory())
                    setDirAndUpdate(file);
            }

        };
        View.OnLongClickListener itemLongClickListener = new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ViewHolder holder = (ViewHolder) v.getTag();
                if (controlFragment.mListener != null) {
                    boolean die = mListener.onListFragmentInteraction(holder.mItem, v);
                    if (!die) die = mListener.onFileItemLongClick(holder.mItem, v);
                    if (die) return true;
                }

                //显示长按菜单
                PopupMenu popmenu = new PopupMenu(ExplorerFragment.this.getContext(), v);
                popmenu.inflate(R.menu.file_item_longclick);
                Menu menu = popmenu.getMenu();
                Intent fileIntent = new Intent();
                fileIntent.putExtra(KEY_FILE, holder.mItem.path);
                menu.findItem(R.id.item_delete).setIntent(fileIntent);
                menu.findItem(R.id.item_rename).setIntent(fileIntent);
                menu.findItem(R.id.item_cut).setIntent(fileIntent);
                popmenu.setOnMenuItemClickListener(ExplorerFragment.this);
                popmenu.show();
                return true;
            }
        };
        CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ViewHolder holder = (ViewHolder) buttonView.getTag();
                if (mListener != null)
                    mListener.onListFragmentInteraction(holder.mItem, buttonView);

                //改变已选择好的文件的数目
                holder.mItem.checked = isChecked;
                refreshConfirmButtonVisibility();
                controlFragment.refreshCheckItemCount();
            }
        };

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            holder.mItem = mValues.get(position);
            holder.mContentView.setText(mValues.get(position).fileName);
            //如果不是文件夹，隐藏文件夹图标
            if (!(new File(mValues.get(position).path)).isDirectory())
                holder.iconView.setVisibility(View.GONE);
            holder.mView.setTag(holder);
            holder.mView.setOnClickListener(itemClickListener);
            holder.mView.setOnLongClickListener(itemLongClickListener);
            holder.checkBox.setTag(holder);
            holder.checkBox.setOnCheckedChangeListener(checkedChangeListener);
        }

        ExplorerFragment controlFragment = ExplorerFragment.this;

        public int getCheckedItemCount() {
            int result = 0;
            for (int i = 0; i < mValues.size(); i++) {
                if (mValues.get(i).checked) result++;
            }
            return result;
        }

        void refreshConfirmButtonVisibility() {
            if (chooseResult().size()>0) {//符合条件的选择数目大于0
                confirmButtonContainer.setVisibility(View.VISIBLE);
            }
            else{
                confirmButtonContainer.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }

        List<FileItem> getFiles() {
            return this.mValues;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            final View mView;
            final TextView mContentView;
            final View iconView;
            final CheckBox checkBox;
            FileItem mItem;

            ViewHolder(View view) {
                super(view);
                mView = view;
                mContentView = (TextView) view.findViewById(R.id.content);
                iconView = view.findViewById(R.id.biaozhi);
                checkBox = (CheckBox) view.findViewById(R.id.checkbox_select);

            }

            @Override
            public String toString() {
                return super.toString() + " '" + mContentView.getText() + "'";
            }
        }
    }

}


